<template>
  <jke-modal
    :visible.sync="jkeForm.visible"
    :width="1200"
    :title="jkeForm.title"
    :fullscreen.sync="jkeForm.fullscreen"
    :switchFullscreen="jkeForm.switchFullscreen"
  >
    <!--  -->
    <crumbs @goBack="goBack" :superiorMenu="['库存管理', '库存盘点']" currentMenu="盘点单详情"> </crumbs>
    <div class="uni-card">
      <div class="bd-line"></div>
      <div class="item-wrap1">
        <div class="detail-item" style="width: 35%">
          <p class="subtitle">盘点单号</p>
          <p class="secondary-text">{{ detailInfo.inventoryCode || '-' }}</p>
        </div>
        <div class="detail-item" style="width: 35%">
          <p class="subtitle">盘点仓库</p>
          <p class="secondary-text">
            {{ detailInfo.warehouseCodeName || '-' }}
          </p>
        </div>
        <div class="detail-item" style="width: 15%">
          <p class="subtitle">盘点人</p>
          <p class="secondary-text">{{ detailInfo.inventoryUser || '-' }}</p>
        </div>
        <div class="detail-item" style="width: 15%">
          <p class="subtitle" style="text-align: right">状态</p>
          <p class="secondary-text" :style="{ color: setColor(detailInfo.inventoryStatus), fontSize: '16px', textAlign: 'right' }">
            {{ detailInfo.inventoryStatus }}
          </p>
        </div>
        <div class="fiexBox" style="width: auto">
          <flow-status style="text-align: right" title="审批状态" ids="WMS_WAREHOUSE_INVENTORY" :flowStatusText="detailInfo.flowStatusText"
            :flowStatus="detailInfo.flowStatus"></flow-status>
        </div>
      </div>
      <div class="item-wrap">
        <div class="detail-item" style="width: 35%">
          <p class="subtitle">盘点开始时间</p>
          <p class="secondary-text">{{ detailInfo.createTime || '-' }}</p>
        </div>
        <div class="detail-item" style="width: 35%">
          <p class="subtitle">盘点结束时间</p>
          <p class="secondary-text">
            {{ detailInfo.updateTime || '-' }}
          </p>
        </div>
        <div class="detail-item" style="width: 15%"></div>
        <div class="detail-item" style="width: 15%"></div>
      </div>
    </div>
    <div class="cards-box">
      <a-card title="盘点物品" :bordered="false" style="margin-top: 12px">
        <a-tabs default-active-key="0" @change="changeCurrent">
          <a-tab-pane :disabled="isLoading" key="0" :tab="tabAll"> </a-tab-pane>
          <a-tab-pane :disabled="isLoading" key="1" :tab="tabAbNormal"></a-tab-pane>
          <a-tab-pane :disabled="isLoading" key="2" :tab="tabNormal"></a-tab-pane>
        </a-tabs>
        <j-editable-table ref="goodsTable" :loading="goodsTable.loading" :columns="goodsTable.columns" :dataSource="goodsTable.dataSource" :maxHeight="300"
          :rowNumber="false" :rowSelection="false">
          <template v-slot:picUrl="props">
            <div class="pic-f">
              <div class="pic-l">
                <img :src="props.value" alt="" class="imgClass" />
              </div>
              <div class="pic-r">
                <div>{{ setCode(props) }}</div>
                <div>{{ setName(props) }}</div>
                <div>{{ setSpec(props) }}</div>
              </div>
            </div>
          </template>
          <template v-slot:goodsQualifiedNum="props">
            <div style="width:120px;">
              <div style="width:120px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;" :title="`合格品: ${props.value}${setUnit(props)}`">合格品:
                {{ props.value }}{{ setUnit(props) }}</div>
              <div style="width:120px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;" :title="`报废品: ${setGoodsScrapNum(props)}${setUnit(props)}`">报废品:
                {{ setGoodsScrapNum(props) }}{{ setUnit(props) }}</div>
            </div>
          </template>
          <template v-slot:inventoryGoodsQualifiedNum="props">
            {{ props.value }} <span v-if="props.value">{{ setUnit(props) }}</span>
          </template>
          <template v-slot:inventoryGoodsScrapNum="props">
            {{ props.value }}<span v-if="props.value">{{ setUnit(props) }}</span>
          </template>
          <template v-slot:inventoryResult="props">
            <div class="comp-normal" style="color:red" :title="props.value">{{ props.value }}</div>
          </template>
          <template v-slot:action="props">
            <div v-if="checkStatus(props)">
              <a-button type="link" @click="handleAlready(props)">标记为已处理</a-button>
              <a-dropdown>
                <a class="ant-dropdown-link" @click.prevent> 更多 </a>
                <a-menu slot="overlay">
                  <a-menu-item>
                    <div class="itemBox" @click="clickOut">
                      <img src="@/assets/img/public-add.png" alt="" /> 新建出库单
                    </div>
                  </a-menu-item>
                  <a-menu-item>
                    <div class="itemBox" @click="clickIn">
                      <img src="@/assets/img/public-add.png" alt="" /> 新建入库单
                    </div>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </div>
          </template>
        </j-editable-table>
        <div style="display: inline-block; float: right">
          <a-pagination :total="getGoodsListPage.total" v-model="pagination3.current" :page-size-options="pagination3.pageSizeOptions" :page-size="pagination3.pageSize"
            @change="(current, pageSize) => onChangePage(current, pageSize,'pagination3')"
            @showSizeChange="(current, pageSize) => onShowSizeChange(current, pageSize,'pagination3')" show-quick-jumper show-size-changer v-if="tabStatus == 'normal'" />
          <a-pagination :total="getGoodsListPage.total" v-model="pagination2.current" :page-size-options="pagination2.pageSizeOptions" :page-size="pagination2.pageSize"
            @change="(current, pageSize) => onChangePage(current, pageSize,'pagination2')"
            @showSizeChange="(current, pageSize) => onShowSizeChange(current, pageSize,'pagination2')" show-quick-jumper show-size-changer
            v-else-if="tabStatus == 'abnormal'" />
          <a-pagination :total="getGoodsListPage.total" v-model="pagination1.current" :page-size-options="pagination1.pageSizeOptions" :page-size="pagination1.pageSize"
            @change="(current, pageSize) => onChangePage(current, pageSize,'pagination1')"
            @showSizeChange="(current, pageSize) => onShowSizeChange(current, pageSize,'pagination1')" show-quick-jumper show-size-changer v-else />
        </div>
      </a-card>
    </div>
    <Examine  v-if="detailInfo.flowInstId" type="2" :id="detailInfo.flowInstId" ref="examine" />
  </jke-modal>
</template>
<script>
import { FormTypes } from '@/utils/JEditableTableUtil'
import crumbs from '@/components/crumbs.vue'
import { getFileListByIds } from '@/api/api'
import FileDetail from '@/components/fileActions/FileDetail'
import { returnMaterialQueryById } from '@/api/goodsManagement'
import { API } from '@/api/requestFzs'
import { numFormat } from '@/utils/util'
import LogoVue from '../../../components/tools/Logo.vue'
import { apiBaseUrlDownload } from '@/utils/request'
import FlowStatus from '@/pubComponent/FlowStatus'
import { APILX } from '@/api/requestLx'
import Examine from '@/components/examine'
const goodsPagination = {
  current: 1,
  total: 0,
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30', '40', '50'],
}
export default {
  data() {
    return {
      jkeForm: {
        title: '盘点单详情',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      domianURL: apiBaseUrlDownload, //表格图片展示
      isLoading: false, //防止tab来回切换 导致数据重复渲染
      tabAll: '全部',
      tabAbNormal: '盘点异常库存（0）',
      tabNormal: '盘点正常库存（0）',
      getGoodsListPage: Object.assign({}, goodsPagination),
      pagination1: Object.assign({}, goodsPagination),
      pagination2: Object.assign({}, goodsPagination),
      pagination3: Object.assign({}, goodsPagination),
      tabStatus: '',
      queryTd: '',
      columns: [
        {
          title: 'goodsId',
          width: '20%',
          key: 'goodsId',
          type: FormTypes.hidden,
        },
        {
          title: 'assistUnit',
          width: '20%',
          key: 'assistUnit',
          type: FormTypes.hidden,
        },
        {
          title: 'goodsCode',
          width: '20%',
          key: 'goodsCode',
          type: FormTypes.hidden,
        },
        {
          title: 'goodsName',
          width: '20%',
          key: 'goodsName',
          type: FormTypes.hidden,
        },
        {
          title: 'spec',
          width: '20%',
          key: 'spec',
          type: FormTypes.hidden,
        },
        {
          title: 'goodsScrapNum',
          width: '20%',
          key: 'goodsScrapNum',
          type: FormTypes.hidden,
        },
        {
          title: '物品编号|物品名称|规格',
          width: '250px',
          key: 'picUrl',
          type: FormTypes.slot,
          slotName: 'picUrl',
        },
        {
          title: '账面库存',
          width: '150px',
          key: 'goodsQualifiedNum',
          type: FormTypes.slot,
          slotName: 'goodsQualifiedNum',
        },
        {
          title: '账面库存(F)',
          width: '150px',
          key: 'goodsQualifiedNumTextAssistUnit',
        },

        {
          title: '不含税单价（元）',
          width: '150px',
          key: 'unitPriceExcludingTaxText',
        },
        {
          title: '账面金额（元）',
          width: '150px',
          key: 'amountExcludingTaxText',
        },

        {
          title: '合格品',
          width: '150px',
          key: 'inventoryGoodsQualifiedNum',
          type: FormTypes.slot,
          slotName: 'inventoryGoodsQualifiedNum',
        },
        {
          title: '报废品',
          width: '150px',
          key: 'inventoryGoodsScrapNum',
          type: FormTypes.slot,
          slotName: 'inventoryGoodsScrapNum',
        },
        {
          title: '合格品(F)',
          width: '150px',
          key: 'inventoryGoodsQualifiedNumTextAssistUnit',
        },
        {
          title: '报废品(F)',
          width: '150px',
          key: 'inventoryGoodsScrapNumTextAssistUnit',
        },
        {
          title: '盘点金额（元）',
          width: '150px',
          key: 'pdAmountExcludingTaxText',
        },
        {
          title: '盘点状态',
          width: '120px',
          key: 'statusText',
        },
        {
          title: '盘点结果',
          width: '260px',
          key: 'inventoryResult',
          type: FormTypes.slot,
          slotName: 'inventoryResult',
        },
        // {
        //   title: '操作',
        //   // width: '10%',
        //   key: 'handleStatus',
        //   type: FormTypes.slot,
        //   slotName: 'action',
        // },
      ],
      goodsTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: 'goodsId',
            width: '20%',
            key: 'goodsId',
            type: FormTypes.hidden,
          },
          {
            title: 'assistUnit',
            width: '20%',
            key: 'assistUnit',
            type: FormTypes.hidden,
          },
          {
            title: 'goodsCode',
            width: '20%',
            key: 'goodsCode',
            type: FormTypes.hidden,
          },
          {
            title: 'goodsName',
            width: '20%',
            key: 'goodsName',
            type: FormTypes.hidden,
          },
          {
            title: 'spec',
            width: '20%',
            key: 'spec',
            type: FormTypes.hidden,
          },
          {
            title: 'goodsScrapNum',
            width: '20%',
            key: 'goodsScrapNum',
            type: FormTypes.hidden,
          },
          {
            title: '物品编号|物品名称|规格',
            width: '250px',
            key: 'picUrl',
            type: FormTypes.slot,
            slotName: 'picUrl',
          },
          {
            title: '账面库存',
            width: '150px',
            key: 'goodsQualifiedNum',
            type: FormTypes.slot,
            slotName: 'goodsQualifiedNum',
          },
          {
            title: '账面库存(F)',
            width: '150px',
            key: 'goodsQualifiedNumTextAssistUnit',
            defaultValue: '-',
          },
          {
            title: '不含税单价（元）',
            width: '150px',
            key: 'unitPriceExcludingTaxText',
          },
          {
            title: '账面金额（元）',
            width: '150px',
            key: 'amountExcludingTaxText',
          },
          {
            title: '合格品',
            width: '150px',
            key: 'inventoryGoodsQualifiedNum',
            type: FormTypes.slot,
            slotName: 'inventoryGoodsQualifiedNum',
          },
          {
            title: '报废品',
            width: '150px',
            key: 'inventoryGoodsScrapNum',
            type: FormTypes.slot,
            slotName: 'inventoryGoodsScrapNum',
          },
          {
            title: '合格品(F)',
            width: '150px',
            key: 'inventoryGoodsQualifiedNumTextAssistUnit',
          },
          {
            title: '报废品(F)',
            width: '150px',
            key: 'inventoryGoodsScrapNumTextAssistUnit',
          },
          {
            title: '盘点金额（元）',
            width: '150px',
            key: 'pdAmountExcludingTaxText',
          },
          {
            title: '盘点状态',
            width: '120px',
            key: 'statusText',
          },
          {
            title: '盘点结果',
            width: '260px',
            key: 'inventoryResult',
            type: FormTypes.slot,
            slotName: 'inventoryResult',
          },
          // {
          //   title: '操作',
          //   // width: '10%',
          //   key: 'handleStatus',
          //   type: FormTypes.slot,
          //   slotName: 'action',
          // },
        ],
      },
      numFormat,
      detailInfo: {},
    }
  },
  components: {
    crumbs,
    FileDetail,
    Examine,
    FlowStatus,
  },
  methods: {
    handleAlready(props) {
      let tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      let that = this
      that.$antdConfirm({
        title: '确定要标记为已处理吗?',
        content: `建议新建出库单或入库单后再标记为 "已处理".`,
        onOk() {
          APILX.wmsWarehouseInventoryUpdateException(tableValue.id).then((res) => {
            if (res.code == 200) {
              that.$antdMessage.success('已标记为已处理！')
              that.getTable()
            } else {
              that.$antdMessage.error(res.message)
            }
          })
        },
        onCancel() {},
      })
    },
    clickOut() {
      let outObj = {
        fromPage: 'stockCheckDetail',
        id: this.queryTd,
      }
      this.$openWay(this, true, '/buildOutStock', outObj)
    },
    clickIn() {
      let inObj = {
        fromPage: 'stockCheckDetail',
        id: this.queryTd,
      }
      this.$openWay(this, true, '/buildInStock', inObj)
    },
    checkStatus(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.status == 'abnormal' && tableValue.handleStatus == '0') {
        return true
      }
      return false
    },
    getAbNormal() {
      this.getTableNum('abnormal')
    },
    getNormal() {
      this.getTableNum('normal')
    },
    // 分页
    onChangePage(current, pageSize, key) {
      console.log('current, pageSize', current, pageSize)
      this[key].current = current
      this.getGoodsListPage.current = current
      this.getTable()
    },
    onShowSizeChange(current, pageSize, key) {
      console.log('current, pageSize', this.tabStatus)
      this[key].pageSize = pageSize
      this[key].current = current
      this.getGoodsListPage.pageSize = pageSize
      this.getGoodsListPage.current = current
      this.getTable()
    },
    // tab分页
    changeCurrent(key) {
      if (key == '0') {
        this.tabStatus = ''
        this.columns[this.columns.length - 1].type = FormTypes.slot
        this.goodsTable.columns = JSON.parse(JSON.stringify(this.columns))
        console.log('this.pagination1:', this.pagination1)
        this.getGoodsListPage = this.pagination1
      } else if (key == '1') {
        this.tabStatus = 'abnormal'
        this.columns[this.columns.length - 1].type = FormTypes.slot
        this.goodsTable.columns = JSON.parse(JSON.stringify(this.columns))
        console.log('this.pagination2:', this.pagination2)
        this.getGoodsListPage = this.pagination2
      } else if (key == '2') {
        this.tabStatus = 'normal'
        this.columns[this.columns.length - 1].type = FormTypes.hidden
        let newArr = JSON.parse(JSON.stringify(this.columns))
        this.goodsTable.columns = newArr.filter((item) => {
          return item.title != '操作'
        })
        console.log('this.pagination3:', this.pagination3)
        this.getGoodsListPage = this.pagination3
      }
      this.getTable()
    },
    setColor(s) {
      let cor = {
        1: '#888888', //黑色
        盘点中: '#1890FF', //蓝色
        盘点正常: '#00B042', //绿色
        盘点异常: '#ff4d4f', //红色
      }
      return cor[s] || ''
    },
    /* 面包屑返回 */
    goBack() {
      this.jkeForm.visible = false
    },
    initDetail(id) {
      this.jkeForm.visible = true
      this.tabStatus = ''
      this.queryTd = id
      this.getNormal()
      this.getAbNormal()
      this.getTable()
      APILX.warehouseInventoryGetContinueInventoryInfo(this.queryTd).then((res) => {
        if (res.code == 200) {
          this.detailInfo = res.result
        } else {
          this.$antdMessage.error(res.result)
        }
      })
    },
    getTable() {
      let param = {
        id: this.queryTd,
        status: this.tabStatus,
        pageNo: this.getGoodsListPage.current,
        pageSize: this.getGoodsListPage.pageSize,
      }
      this.goodsTable.dataSource = []
      this.isLoading = true
      APILX.getWmsInventoryGoodsList(param).then((res) => {
        if (res.code == 200) {
          // console.log(res, '进来了没warehouseInventoryUnCompleteList')
          let tableData = res.result.records
          // this.goodsTable.dataSource = []
          tableData.forEach((item) => {
            item.inventoryGoodsScrapNumTextAssistUnit = item.inventoryGoodsScrapNumTextAssistUnit || '-'
            item.inventoryGoodsQualifiedNumTextAssistUnit = item.inventoryGoodsQualifiedNumTextAssistUnit || '-'
            item.goodsQualifiedNumTextAssistUnit = item.goodsQualifiedNumTextAssistUnit || '-'
            item.inventoryResult = item.inventoryResult || '-'
            item.statusText = item.statusText || '-'
            if (item.attachment) {
              let ids = item.attachment
              getFileListByIds({ ids }).then((res) => {
                if (res.code == 200) {
                  let fileList = ''
                  fileList = res.result
                  if (fileList.length > 0) {
                    item.picUrl = this.domianURL + fileList[0].uri
                    this.goodsTable.dataSource.push(item)
                  } else {
                    item.picUrl = require('../../../assets/img/noPicture.jpg')
                    this.goodsTable.dataSource.push(item)
                  }
                }
              })
            } else {
              item.picUrl = require('../../../assets/img/noPicture.jpg')
              this.goodsTable.dataSource.push(item)
            }
            if (item.inventoryGoodsQualifiedNum == '-') {
              item.inventoryGoodsQualifiedNum = 0.0
            }
            if (item.inventoryGoodsScrapNum == '-') {
              item.inventoryGoodsScrapNum = 0.0
            }
          })
          // console.log(this.goodsTable.dataSource, 'this.goodsTable.dataSource')
          if (param.status == 'abnormal') {
            this.tabAbNormal = `盘点异常库存（${res.result.total}）`
            // console.log(this.tabAbNormal, '走 this.tabAbNormal')
          } else if (param.status == 'normal') {
            this.tabNormal = `盘点正常库存（${res.result.total} ）`
            // console.log(this.tabNormal, '走 this.tabNormal', res.result.total)
          }
          this.getGoodsListPage.total = res.result.total
          setTimeout(() => {
            this.isLoading = false
          }, 1000)
        } else {
          this.$antdMessage.error(res.message)
          this.isLoading = false
        }
      })
    },
    getTableNum(status) {
      let param = {
        id: this.queryTd,
        status,
      }
      APILX.getWmsInventoryGoodsList(param).then((res) => {
        if (res.code == 200) {
          if (status == 'abnormal') {
            this.tabAbNormal = `盘点异常库存（${res.result.total}）`
          } else if (status == 'normal') {
            this.tabNormal = `盘点正常库存（${res.result.total} ）`
          }
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    setGoodsScrapNum(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.goodsScrapNum) {
        return tableValue.goodsScrapNum
      } else {
        return ''
      }
    },
    setUnit(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.assistUnit) {
        return tableValue.assistUnit
      } else {
        return ''
      }
    },
    setSpec(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.spec) {
        return tableValue.spec
      } else {
        return '-'
      }
    },
    setName(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.goodsName) {
        return tableValue.goodsName
      } else {
        return ''
      }
    },
    setCode(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.goodsCode) {
        return tableValue.goodsCode
      } else {
        return ''
      }
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
.itemBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  img {
    width: 16px;
    height: 16px;
    margin-right: 10px;
  }
}
.item-wrap {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}
.item-wrap1 {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  position: relative;
}
.item-wrap:nth-of-type(n + 2) {
  margin-top: 40px;
}
.detail-item {
  width: 30%;
}
.uni-card {
  padding: 24px 40px;
  margin: -12px -12px 0;
  background: #fff;
}
.bd-line {
  height: 1px;
  background: @greyBorder;
  margin: -12px -40px 24px -40px;
}
.cards-box {
  // height: calc(100vh - 300px);
  // overflow-y: scroll;
  margin-bottom: 20px;
}
.pic-f {
  display: flex;
  padding: 10px;
  flex: 1;
  .pic-l {
    display: inline-block;
    margin-right: 14px;
  }
  .pic-r {
    flex-direction: column;
    justify-content: space-between;
    display: inline-block;
    font-size: 14px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #444444;
  }
}
.imgClass {
  width: 60px;
  height: 60px;
  border-radius: 6px;
}
.fiexBox {
  position: absolute;
  top: 15px;
  right: -5px;
}
</style>
